import 'dart:io';
import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/extension/ex_widget.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/pages/message/common_input.dart';
import 'package:flutter_massage/pages/message/index.dart';
import 'package:flutter_massage/pages/message/message_detail_logic.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/values/colors.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../generated/assets.dart';

class MessageDetailPage extends GetView<MessageDetailLogic> {
  MessageDetailPage({required this.chatId, required this.name, super.key});

  final String chatId;
  final String name;

  final showInputBottom = ValueNotifier(-1);
  double lastViewBottom = 0;
  double keyboardHeight = 0;
  double insertBottom = MediaQueryData.fromWindow(window).viewInsets.bottom;

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      titleStr: name,
      child: GetBuilder<MessageDetailLogic>(
        init: MessageDetailLogic(chatId),
        assignId: true,
        builder: (logic) {
          return Column(
            children: [
              Align(
                alignment: Alignment.topCenter,
                child: Listener(
                  onPointerMove: (PointerMoveEvent event) {
                    CommonOperate.hideKeyboard();
                  },
                  child: ListView.separated(
                    padding: EdgeInsets.symmetric(vertical: 10.w),
                    controller: logic.scrollController,
                    itemCount: logic.messageList.length,
                    itemBuilder: (BuildContext context, int index) {
                      final double w = 40.w;
                      String avatar = XydUserService.avatar;
                      Widget avatarWidget;
                      bool exist = File(avatar).existsSync();
                      if (exist) {
                        avatarWidget = Image.file(File(avatar), fit: BoxFit.cover, width: w, height: w);
                      } else {
                        avatarWidget = Assets.svgMyIconPlaceholder.toSvg(width: w, height: w);
                      }

                      return Row(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Container(
                            constraints: BoxConstraints(maxWidth: ScreenUtil().screenWidth * 0.6),
                            padding: EdgeInsets.all(8.w),
                            decoration: CommonDecoration.getShapeDecoration(radius: 6.w, bg: '31C3A3'.toColor),
                            child: TextWidget.moreLine(
                              text: (controller.messageList[index].message ?? ''),
                              fontSize: 15,
                              color: Colors.white,
                            ),
                          ).paddingRight(10.w).flexible(),
                          ClipRRect(
                            borderRadius: BorderRadius.circular(w),
                            child: avatarWidget,
                          ),
                        ],
                      ).paddingRight(16.w);
                    },
                    separatorBuilder: (BuildContext context, int index) => Container(height: 15.w),
                    reverse: true,
                    shrinkWrap: false,
                  ),
                ),
              ).expanded(),
              _buildInput(),
            ],
          );
        },
      ),
    );
  }

  Widget _buildInput() {
    return CommonInputListener(
      inputChange: (BuildContext context, double inputHeight, bool inputClose) {
        if (inputClose == false) {
          ///键盘弹出
          controller.scrollController.jumpTo(0);
        }

        ///输入法
        var input = inputComponent(context, inputHeight, inputClose);

        ///其他操作（发图等）
        var bottom = inputBottomComponent(context, inputHeight, inputClose);

        return GestureDetector(
          //防止点击关闭
          onTap: () {},
          child: Container(
            color: AppColors.grayF8,
            child: Column(children: [input, bottom]),
          ),
        );
      },
    );
  }

  Widget inputComponent(BuildContext context, double inputHeight, bool inputClose) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.w),
      child: Row(
        children: [
          ImInput(
            controller: controller.textEditingController,
            focusNode: controller.focusNode,
            scrollController: controller.inputScrollController,
            onEditingComplete: controller.sendMessage,
          ).paddingRight(8.w).expanded(),
          ButtonWidget.text(
            '发送',
            backgroundColor: '31C3A3'.toColor,
            width: 46.w,
            height: 30.w,
            borderRadius: 4.w,
            alignment: Alignment.center,
            textColor: Colors.white,
            onTap: controller.sendMessage,
          ),
        ],
      ),
    );
  }

  Widget inputBottomComponent(BuildContext context, double inputHeight, bool inputClose) {
    return ValueListenableBuilder(
      valueListenable: showInputBottom,
      builder: (context, v, _) {
        var safeBottomHeight = ScreenUtil().bottomBarHeight * 0.5;
        var bottom = insertBottom;

        if (inputHeight != 0) keyboardHeight = inputHeight;

        var changeHeight = max(bottom, safeBottomHeight);
        Widget child = SizedBox(height: changeHeight);

        lastViewBottom = bottom;

        return AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
          height: changeHeight,
          child: Stack(children: [Positioned(left: 0, right: 0, top: 0, child: child)]),
        );
      },
    );
  }
}
